package com.ling.algorithm;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * abortPolicy(默认)：直接抛出 RejectedExecutionException
 * CallerRunPolicy: "调用者运行“ 一种调节机制，该策略即不会抛弃任务， 也不会抛出异常， 而是将某些任务回退到调用者， 从而降低新任务的流量（谁让你来找到线程池的就退回给谁）
 * discardOldestPolicy: 抛弃队列中等待最久的任务， 然后把当前任务加入队列中尝试在其提交任务
 * discardPolicy: 该策略默默地丢弃无法处理的任务， 不予任何处理也不报异常， 如果允许任务丢失， 这是最好的一种策略
 */
public class MyThreadPoolDemo {

    public static void main(String[] args) {
        System.out.println(Runtime.getRuntime().availableProcessors());
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 5, 2L, TimeUnit.MICROSECONDS, new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),new ThreadPoolExecutor.CallerRunsPolicy());

        try {
            for (int i = 0; i < 10; i++) {
                threadPoolExecutor.execute(()->{
                    try {
                        Thread.sleep(5);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(Thread.currentThread().getName()+"办理业务");
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPoolExecutor.shutdown();
        }
    }
}
